package com.soriya.nestlive.screen.channel

import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.os.Build
import android.provider.MediaStore
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.Icon
import androidx.compose.material.LocalContentColor
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldColors
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.DeleteForever
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.hilt.navigation.compose.hiltViewModel
import com.soriya.nestlive.component.CustomEditText
import com.soriya.nestlive.component.CustomImage
import com.soriya.nestlive.component.CustomTextArea
import com.soriya.nestlive.component.ScreenColumnContent
import com.soriya.nestlive.constant.UIValue
import com.soriya.nestlive.model.form.CreateChannelForm
import com.soriya.nestlive.util.ToastUtil
import com.soriya.nestlive.util.WindowUtil
import com.soriya.nestlive.viewmodel.ChannelModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.io.File

private val PERMISSIONS = arrayOf(
    Manifest.permission.READ_EXTERNAL_STORAGE,
    Manifest.permission.WRITE_EXTERNAL_STORAGE
)

@Composable
fun ChannelFromScreen(
    back: () -> Unit
) = ScreenColumnContent(
    horizontalAlignment = Alignment.CenterHorizontally,
    modifier = Modifier.padding(vertical = UIValue.VERTICAL_PADDING)
) {
    val context = LocalContext.current as Activity
    val widthDp = WindowUtil.getScreenWidthToDp(context)

    var cover: File? by remember {
        mutableStateOf(null)
    }

    var about by remember {
        mutableStateOf("")
    }

    var channelName by remember {
        mutableStateOf("")
    }

    val model: ChannelModel = hiltViewModel()

    val coroutineScope = rememberCoroutineScope()

    val launcher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent(),
        onResult = { uri ->
            uri?.let {
                val cursor = context.contentResolver.query(uri, null, null, null, null)
                cursor?.let {
                    it.moveToNext()
                    val columnIndex = it.getColumnIndex(MediaStore.Images.Media.DATA)
                    val path = it.getString(columnIndex)
                    cover = File(path)
                    it.close()
                }
            }
        }
    )

    // 申请权限
    val permissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestMultiplePermissions(),
        onResult = { isGranteds ->
            var allGranted = false
            for ((_, isGranted) in isGranteds) {
                allGranted = isGranted
            }
            if (allGranted) {
                launcher.launch("image/*")
                ToastUtil.show(context, "授权成功")
            } else {
                ToastUtil.show(context, "授权失败")
            }
        }
    )

    Box(
        contentAlignment = Alignment.Center,
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(UIValue.MEDIUM_RADIUS))
            .border(1.dp, MaterialTheme.colors.surface, RoundedCornerShape(UIValue.MEDIUM_RADIUS))
            .height(widthDp.dp / 3)
            .clickable {
                // 判断权限
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    var check = PackageManager.PERMISSION_GRANTED
                    for (permission in PERMISSIONS) {
                        check = ContextCompat.checkSelfPermission(context, permission)
                        if (check != PackageManager.PERMISSION_GRANTED) break
                    }
                    val hasPermission = check == PackageManager.PERMISSION_GRANTED
                    if (!hasPermission) {
                        // 没有全部的权限，申请权限
                        permissionLauncher.launch(PERMISSIONS)
                    } else {
                        launcher.launch("image/*")
                    }
                }
            }
    ) {
        CompositionLocalProvider (LocalContentColor provides MaterialTheme.colors.surface) {
            if (cover == null) {
                Icon(imageVector = Icons.Outlined.Add, contentDescription = "Upload Cover", modifier = Modifier.size(80.dp))
            } else {
                CustomImage(
                    file = cover!!,
                    contentDescription = "Cover",
                    modifier = Modifier.fillMaxSize()
                )
//                Icon(imageVector = Icons.Outlined.DeleteForever, contentDescription = "Reset Cover", modifier = Modifier.size(80.dp))
            }
        }
    }

    Spacer(modifier = Modifier.height(UIValue.VERTICAL_PADDING.times(2)))

    CustomEditText(
        value = channelName,
        onValueChange = {
            channelName = it
        },
        placeholder = "请输入频道名称",
        shape = RoundedCornerShape(UIValue.SMALLER_RADIUS),
        modifier = Modifier.fillMaxWidth()
    )

    Spacer(modifier = Modifier.height(UIValue.VERTICAL_PADDING.times(2)))

    CustomTextArea(
        value = about,
        onValueChange = {
            about = it
        },
        placeholder = "请输入频道简介",
        shape = RoundedCornerShape(UIValue.SMALLER_RADIUS),
        maxLines = 3,
        minLines = 3,
        modifier = Modifier.fillMaxWidth()
    )

    Spacer(modifier = Modifier.height(UIValue.VERTICAL_PADDING.times(2)))

    Button(
        onClick = {
            if (cover == null || channelName == "" || about == "") {
                ToastUtil.show(context, "请输入完全")
                return@Button
            }

            coroutineScope.launch {
                model.createChannel(
                    CreateChannelForm(cover!!, channelName, about)
                ).collect {
                    ToastUtil.show(context, "创建成功")
                    delay(200)
                    back()
                }
            }
        },
        shape = RoundedCornerShape(50),
        modifier = Modifier.fillMaxWidth()
    ) {
        Text(text = "立即创建")
    }

}